<template>
  <div class="app-container" :style="{backgroundColor: mycolor}">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="商品名称" prop="prodTitle">
        <el-input
          class="prod_input_box"
          style="width: 200px"
          autofocus
          v-model="queryParams.prodTitle"
          placeholder="请输入商品名称"
          prefix-icon="el-icon-goods"
          size="small"
          clearable/>

      </el-form-item>

      <!--      <el-form-item label="商品描述" prop="prodSupplier">-->
      <!--        <el-input-->
      <!--          autofocus-->
      <!--          v-model="queryParams.prodSupplier"-->
      <!--          placeholder="根据描述查询"-->
      <!--          prefix-icon="el-icon-goods"-->
      <!--          size="small"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        >-->
      <!--        </el-input>-->
      <!--      </el-form-item>-->

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          size="small"
          style="width:100px"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          v-hasPermi="['system:role:export']"
          @click="jump"
        >图表</el-button>
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          v-hasPermi="['system:role:export']"
          @click="jump2"
        >图表2</el-button>
      </el-col>

      <el-row class="myColorPicker" @mousedown="moveIcon">
        <el-tooltip class="item" effect="dark" content="主题切换" placement="top">
          <el-color-picker v-model="mycolor" :style="{backgroundColor: mycolor}"></el-color-picker>
        </el-tooltip>

      </el-row>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 添加或修改角色配置对话框 为表格添加key, 解决无法动态更新问题-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

      <el-form
        ref="form"
        :model="addForm"
        label-width="100px"
        :rules="formRules"
        :key="addForm.key">
        <el-form-item label="商品名称" prop="prodTitle">
          <el-input v-model="addForm.prodTitle" placeholder="请输入商品名称" />
        </el-form-item>

        <!--        <el-form-item label="商品型号" prop="prodType">-->
        <!--          <el-select v-model="form.prodVersion">-->
        <!--            <el-option name="supplier" value="4+64G" selected="selected"></el-option>-->
        <!--            <el-option name="supplier" value="6+64G" selected="selected"></el-option>-->
        <!--            <el-option name="supplier" value="6+128G" selected="selected"></el-option>-->
        <!--            <el-option name="supplier" value="8+128G" selected="selected"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="商品型号">
          <!--          <el-row v-for="version in prodVersions">-->
          <!--            <el-checkbox-group v-model="selectedVersions" @change="handleCheckedCitiesChange" style="float: left">-->
          <!--              <el-checkbox  :label="version" v-model="">{{version}}</el-checkbox>-->
          <!--            </el-checkbox-group>-->
          <!--            <input placeholder="请输入价格" style="float: left"></input>-->
          <!--          </el-row>-->
          <br>
          <VersionSelect ref="childRules" :detailList="xiaoMiProdDetailList"></VersionSelect>
          <div v-show="!childRules" style="color: red">请将勾选的价格数量输入完整</div>
        </el-form-item>

        <el-form-item label="分类" style="width:120%;">
          <el-select v-model="addForm.prodCategory">
            <el-option-group label="头部产品" >
              <el-option value="1">Xiaomi手机</el-option>
              <el-option value="2">Redmi红米</el-option>
              <el-option value="3">电视</el-option>
              <el-option value="4">笔记本</el-option>
              <el-option value="5">平板</el-option>
              <el-option value="6">家电</el-option>
              <el-option value="7">路由器</el-option>
            </el-option-group>
            <el-option-group label="管轮区产品">
              <el-option value="8">手机</el-option>
              <el-option value="9">电视</el-option>
              <el-option value="10">笔记本 平板</el-option>
              <el-option value="11">出行 穿戴</el-option>
              <el-option value="12">智能 路由器</el-option>
              <el-option value="13">电源 配件</el-option>
              <el-option value="14">健康 儿童</el-option>
              <el-option value="15">耳机 音响</el-option>
              <el-option value="16">生活 箱包</el-option>
            </el-option-group>
            <el-option-group label="主要产品">
              <el-option value="17">手机</el-option>
              <el-option value="18">电视影音</el-option>
              <el-option value="19">热门</el-option>
              <el-option value="20">出行</el-option>
              <el-option value="21">安防</el-option>
              <el-option value="22">智能热门</el-option>
              <el-option value="23">耳机音响</el-option>
              <el-option value="24">搭配热门</el-option>
              <el-option value="25">充电器</el-option>
              <el-option value="26">配件热门</el-option>
              <el-option value="27">出行</el-option>
              <el-option value="28">周边热门</el-option>
            </el-option-group>
          </el-select>
        </el-form-item>


        <el-form-item label="供应商" prop="prodSupplier_form">
          <el-select v-model="addForm.prodSupplier" placeholder="请选择供应商">
            <el-option value="小米自营" :selected="true"></el-option>
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="当前价格" prop="prodPriceCurrent">-->
        <!--          <el-input v-model.number="form.prodPriceCurrent" placeholder="请输入商品名称" />-->
        <!--        </el-form-item>-->

        <el-form-item label="状态">
          <el-radio-group v-model="addForm.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input style="width: 250px" v-model="addForm.prodDesc" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getRole, delRole, addRole, updateRole, exportRole, dataScope, changeRoleStatus } from "@/api/system/role";
import {getProductList, getProductDetailList, addProduct, updateProduct, changeProdStatus, exportProduct} from '@/api/miprod'

let echarts = require('echarts/lib/echarts')
// 引入柱状图组件
require('echarts/lib/chart/bar')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
import myChart from "@/views/micharts/SellerPage";
import VersionSelect from "@/views/components/VersionSelect";

export default {
  name: "Role",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      //从表详情数据
      xiaoMiProdDetailList:[],
      prodPrice:[],
      prodCount: [],
      //商品详情
      prodDetail: [],
      orgOptions: {},
      //商品价格
      prodVersions: ['4+64G', '6+128G', '8+128G'],
      selectedVersions: [],
      // activeName: 1,
      //图片地址
      picAddress: process.env.VUE_APP_BASE_API,
      // 产品标题
      prodTitle: '',
      //右侧抽屉
      drawer: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      prodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      //颜色选择器默认值
      mycolor: '#DDC6B7',
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prodId: undefined,
        prodTitle: undefined,
        prodSupplier: undefined,
        prodDesc: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        prodTitle: '',
        prodColor: [],
        prodPic: '',
        prodSupplier: '',
        prodDesc: '',
        prodCurrentPrice: 0,
        prodVersion: '',
      },
      addForm:{
        key: undefined,
        prodId: undefined,
        prodTitle: undefined,
        prodVersion: {},
        prodCategory: 2,
        status: undefined,
        prodDesc: undefined
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      //子表单输入验证结果
      childRules: true,
      // 表单校验
      formRules: {
        prodTitle: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        prodCategory: [
          { required: true, message: "商品分类不能为空", trigger: "blur" }
        ],
      },
      fileList: [],
    };
  },
  components:{myChart, VersionSelect},
  created() {
    this.getList();
    //VersionSelect子组件向父组件传参
    this.$bus.$on("receive", (prodPrice, prodCount) =>{
      this.prodPrice = [];
      this.prodCount = [];
      this.prodPrice.push(prodPrice);
      this.prodCount.push(prodCount);
      // console.log(prodPrice, prodCount)
    })
  },

  methods: {
    test(){
      alert("test")
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      //获取商品基本信息
      getProductList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.prodList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    expandChange(row, expandedRows){
      // console.log(expandedRows)
      if (expandedRows.length){
        // console.log("zhankanle ")

        //获取商品详情信息
        getProductDetailList(expandedRows[0].prodId).then(response =>{
          // console.log(response)
          this.prodDetail = response.data;
        })
      }
    },


    //表格内部图片
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    uploadSuccess(response){
      this.$message({
        message: "图片["+response.data.split('/').pop()+"]上传成功",
        type: "success"
      })
      this.getList();
    },
    moveIcon(e){
      console.log(e)
    },

    // 角色状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "上架" : "下架";
      this.$modal.confirm('确认要' + text + '产品[' + row.prodTitle + ']么？').then(function() {
        return changeProdStatus(row.prodId, row.status);
      }).then(() => {
        this.$message("商品["+row.prodTitle+"]"+text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.addForm = {
        prodTitle: undefined,
        prodVersion: undefined,
        prodColor: [],
        prodSupplier: undefined,
        prodPriceCurrent: undefined,
        status: "0",
        prodDesc: undefined
      };
      this.resetForm("addForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.addForm.prodId = undefined;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.prodId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addForm.key = 0;
      this.open = true;
      this.title = "添加商品";
      this.xiaoMiProdDetailList = undefined;

    },
    /** 修改按钮操作 */
    handleUpdate(row){
      this.reset();
      this.addForm.key = 1;
      let prodId = row.prodId || this.ids[0]
      this.queryParams.prodId = prodId;
      getProductList(this.addDateRange(this.queryParams)).then(response => {
        this.addForm = response.rows[0];
        this.xiaoMiProdDetailList = response.rows[0].xiaoMiProdDetailList;
        this.addForm.prodCategory = response.rows[0].prodCategory;
        this.open = true;
        this.title = "修改角色";
      });
    },

    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId);
      getRole(row.roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          roleDeptTreeselect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配数据权限";
      });
    },
    /** 分配用户操作 */
    handleAuthUser: function(row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    // checkChildRules(){
    //
    //   this.childRules = this.$refs["childRules"].validateForm();
    //   // console.log("state:", this.childRules)
    // },

    /** 提交按钮 */
    submitForm: function(formName){
      if(confirm("确认提交信息吗?")){
        this.childRules = this.$refs["childRules"].validateForm();
        //[{'4+64':[{prodPrice: 12, prodCount: 3339}, {'4+64':[{prodPrice: 12, prodCount: 3339},{'4+64':[{prodPrice: 12, prodCount: 3339}]
        this.$refs[formName].validate(valid =>{

          if (valid && this.childRules){
            let obj = {}
            for(let key in this.prodPrice[0]){
              obj[key] = {'prodPrice': this.prodPrice[0][key], 'prodCount': this.prodCount[0][key]}
            }
            this.addForm.prodVersion = obj;

            if(this.addForm.prodId !== undefined){
              //删除修改之前查询到addForm的多余元素xiaoMiProdDetailList
              delete this.addForm['xiaoMiProdDetailList']
              updateProduct(this.addForm).then(response => {
                if (response.code === 200){
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.queryParams.prodId = undefined;
                  this.getList();
                }
              })
            }else{
              // 发送请求添加数据
              addProduct(this.addForm).then(response =>{
                console.log(response)
                if (response.code === 200){
                  this.$message({
                    message: '恭喜你, 商品添加成功!',
                    type: 'success'
                  });
                  this.open = false;
                }else {
                  this.$message.error('商品添加失败!');
                }
              })
            }
          }
        })
      }
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.roleId !== undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function() {
        return delRole(roleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      // this.queryParams.prodId = this.ids;
      // const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所选用户数据项？').then(() => {
        this.exportLoading = true;
        return exportProduct(this.ids);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    jump(){
      this.$router.push('/SellerPage');
    },
    jump2(){
      this.$router.push('/TrendPage');
    }
  }
};
</script>

<style scoped>
/*页面样式初始化*/
*{
  /*css3属性: 文字放大抗锯齿*/
  font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB, "\5B8B\4F53", sans-serif;
  cursor: url(https://files.cnblogs.com/files/yjlblog/cursor.ico),auto;
}

/*指定按钮以及输入框字体, 初始化页面字体样式*/
button, input {
  font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB, "\5B8B\4F53", sans-serif
}

/*模糊查询外框样式*/
/deep/ .el-input--small .el-input__inner, .el-range-editor--small.el-input__inner {
  border-radius: 17px;
}

/deep/ .el-table{
  background-color: #FF6700;
  border-radius: 5px;
}

/*logo图片滑动特效*/
.header-mi-logo img:hover{
  margin-left: 0;
}

/*颜色选择器样式*/
.el-color-picker {
  background-image: url("../../assets/logo/mi-logo.svg");
  background-position: 95% 50%;
  transition: background-position .3s;
  background-size: 80px;
  border-radius: 14px;
  /*固定定位:fixed*/
  position: fixed;
  top: 20%;
  /*粘性定位*/
  /*position: sticky;*/
  /*top: 200px; */
  z-index: 2; /*定位盒子叠放顺序*/
}

/deep/ .el-color-picker:hover{
  background-position: 5% 50%;
  background-color: #854926;
}

/deep/ .el-color-picker__icon {
  top: 90%;
  left: 50%;
  color: #FFFFFF;
}

/*图片外框样式*/
/deep/ .el-color-picker__trigger {
  font-size: 0;
  cursor: pointer;
  border-radius: 13px;
  border: 2px solid #f2f6fc;
}

/deep/ .demo-block .el-icon-arrow-down {
  font-size: 12px;
  position: absolute;
}

/deep/ .el-color-picker__color {
  border: unset;
}

/deep/ .el-icon-close:before {
  content: unset;
}

/deep/ .el-color-picker__color-inner {
  position: unset;
  display: none;
}

.myColorPicker{
  width: 50px;
  height: 50px;
  position: absolute;
  right: 10%;
}

/deep/ .pagination-container .el-pagination {
  right: 40%;
  position: absolute;
}

/deep/ .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  background-color: rgba(222, 217, 217, 0.5);
}

/*分页样式*/
.pagination-container{
  height: 40px;
  border-radius: 5px;
  text-align: center;
}

.pagination-container:hover{
  height: 40px;
  border-radius: 5px;
  background-color: #e0d5d5;
}

.pagination-container /deep/ .el-pagination {
  left: 50%;
  transform: translate(-50%, -50%);
  right: 0;
  position: absolute;
  text-align: center;
  top: 50%;
}


/*所有按钮样式*/
/deep/ .el-button{
  border-radius: 17px ;
}

/*未选中样式*/
/deep/ .el-pagination.is-background .btn-next{
  border-radius: 79px;
}

/*选中样式*/
/deep/ .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #ff6700;
  border-radius: 100%;
  color: #FFFFFF;
}

/*分页按钮样式*/
/deep/ .el-pagination.is-background .el-pager li {
  border-radius: 100%;
}

/*分页条数外框*/
/deep/ .el-pagination .el-select .el-input .el-input__inner {
  border-radius: 15px;
}

/deep/ .el-pagination__sizes .el-input .el-input__inner:hover {
  border-color: #ff6a03;
}

/*/deep/ .el-pagination.is-background .el-pager li:not(.disabled):hover {*/
/*  background-color: rgba(185, 86, 31, 0.96);*/
/*}*/

/*表格样式*/
.el-table--medium /deep/ .el-table__cell {
  padding: 10px 0;
  height: 50px;
}

.el-table /deep/ .el-table__cell{
  height: 50px;
}

/deep/ .el-table tr {
  background-color: #FFFFFF;
  height: 50px;
}

/*去除图片盒子内边距, 优化分页盒子抖动*/
/deep/ .el-table--medium .el-table__cell {
  padding: 0 0;
  height: 50px;
}

/*下拉级联*/
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

/*下拉级联标题框样式*/
.expand-item-title{
  font-size: 18px;
  font-weight: 700;
  margin-left: 20px;
}

/*下拉级联条目*/
.expand-item-context{
  margin-left: 25px;
  font-size: 16px;
}

/deep/ .el-input--medium .el-input__inner{
  width: 250px;
}

/deep/ .el-input--medium .el-input__inner{
  width: 250px;
}

.com-page{
  width: 100%;
  height: 100%;
  overflow: hidden;
}

</style>
